package com.cloud.service.impl;

import com.alibaba.fastjson.JSON;

import com.cloud.config.ConsumerLogProperties;
import com.cloud.entity.CloudLogRecord;
import com.cloud.service.CloudLogRecordService;
import com.cloud.service.SyncCloudLogRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class SyncCloudLogRecordServiceImpl implements SyncCloudLogRecordService {

    //key是时间 年月日 value是值
    //先判断一下当前时间的上一天是否存在
    //每次插入结束需要清除key
    private static Map<String, List<CloudLogRecord>> logRecordMap = new HashMap<>();

    @Autowired
    private ConsumerLogProperties consumerLogProperties;

    @Autowired
    private CloudLogRecordService cloudLogRecordService;

    @Override
    public void manualBatchSave() {
        Map<String, List<CloudLogRecord>> logRecordMapTem;
        // 使用 SyncSysLogServiceImpl锁，保证定时任务与mq消费者互斥操作
        synchronized (SyncCloudLogRecordServiceImpl.class) {
            logRecordMapTem = logRecordMap;
            logRecordMap = new HashMap<>();
        }
        cloudLogRecordService.saveBatchLog(logRecordMapTem);
    }

    @Override
    public void receiveLogRecord(CloudLogRecord cloudLogRecord) {
        try {
            //当前时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String datetime = sdf.format(new Date());
            Map<String, List<CloudLogRecord>> hashMapTem = null;

            synchronized (SyncCloudLogRecordServiceImpl.class) {
                //判断当前key是否存在，若存在，list继续添加
                //数量大于500，批量的发送，小宇500不发
                //大于500，发送之后，remove掉当前的key
                if (logRecordMap.containsKey(datetime) && CollectionUtils.isNotEmpty(logRecordMap.get(datetime))) {
                    List<CloudLogRecord> logRecords = logRecordMap.get(datetime);
                    logRecords.add(cloudLogRecord);
                    if (logRecords.size() >= consumerLogProperties.getBatchSize()) {
                        log.info("批量list的长度：" + consumerLogProperties.getBatchSize());
                        hashMapTem = logRecordMap;
                        logRecordMap = new HashMap<>();
                    }
                }
                //不存在key，创建一个list，并把当前的对象放进来
                else {
                    List<CloudLogRecord> cloudLogRecords = new ArrayList<>();
                    cloudLogRecords.add(cloudLogRecord);
                    logRecordMap.put(datetime, cloudLogRecords);
                }
            }
            cloudLogRecordService.saveBatchLog(hashMapTem);

        } catch (Exception e) {
            log.error("读取日志错误,源信息:" + JSON.toJSONString(logRecordMap));
            log.error("读取日志错误:", e);
        }
    }
}
